package Fundamental.memory.arrayTest;

public class Circle {
    private int[] kids;
    public Circle(int interval, int kidsCnt){
        this.kids = new int[kidsCnt];
        for (int i = 0; i < kidsCnt ; i++) {
            kids[i] = i ;
        }
    }
    public void print(){
        int i = 0 ;
        while(kids[i] != i){
            i = kids[i];
        }
        System.out.println(i);
    }
    public void count(){
        int cnt = kids.length;
        int i = 0 ;
        int j = 1;
        int left = kids.length;
        int temp = 0 ;
        while(true){

            while(kids[i] != i) {
                i = kids[i];
            }
            if(j >= 3){
               j = 1 ;
               temp = i ;
               // i + 1 位置上是两种情况，一种情况是 kids[i] = i ,
                // 另外一种是 kids[i] != i 这种情况比较麻烦，需要外后找到 kids[i] = i 的那个
                if(kids[(i+1)%kids.length] == (i+1)%kids.length){
                    kids[i] = (i+1)%kids.length;
                    i = (i+1)%cnt ;
                }else{
                    i++;
                    i = i%kids.length;
                    while(kids[i] != i){
                        i = kids[i];
                    }
                    kids[temp] = i%kids.length ;
                }
                left -= 1 ;
//                i = temp;
            }
            if(left == 1){
                break;
            }
            i++;
            i = i%cnt;
            j++;
        }

    }
    public void count2(){
        for (int i = 0; i < kids.length; i++) {
            kids[i] = 1 ;
        }
        int left = kids.length;
        int j = 1;
        int i = 0 ;
        while(left > 1){
            if(kids[i] != 1){
                i++;
                i = i%kids.length;
                continue;
            }
            if(j >= 3){
                j = 0 ;
                kids[i] = 0;
                left -= 1;
            }
            j++;
            i++;
            i = i%kids.length;
        }
        i = 0 ;
        while(i < kids.length){
            if(kids[i] == 1){
                System.out.println(i);
                break;
            }
            i++ ;
        }
    }
    public static void main(String[] args) {
        Circle c = new Circle(3 , 1000);
        c.count();
        System.out.println("count 1:");
        c.print();
        System.out.println("count 2:");
        c.count2();
    }
}
